<?php
/*
 * 会员
 */
namespace app\home\controller;

use app\common\controller\IndexBase;
use think\facade\Session;
use think\facade\Db;
use app\common\model\System;
use yunsms\Yunsms;

class User extends IndexBase
{
    protected function initialize()
    {
        parent::initialize();
    }

    public function index()
    {
        $uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect(url('@login'));
        $data = Db::table('video')->where('type',1)->orderRand()->find();
    	return $this->fetch('',['info'=>Db::table('user')->find($uid),'data'=>$data]);
    }

    //登陆
    public function login()
    {
        is_user_login() && $this->redirect(url('@user')); // 登录直接跳转
        $config = System::get_config_by_code('base');
    	if ($this->request->isPost())
        {
            $param = $this->request->param();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0')
            {
                try{
                    $this->validate($param, 'login');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $config['vercode'] == 1 && empty($param['captcha']) && $this->error('请输入验证码！');
            $config['vercode'] == 1 && !captcha_check($param['captcha']) && $this->error('验证码错误！');
            !empty($param['user_name']) ? $where = function ($query) use ($param){$query->whereOr('name|mobile',trim($param['user_name']));} : $where = 1;
            $user = Db::table('user')->field('id,name,mobile,password,salt,status')->where($where)->find();
            !$user &&  $this->error('账号或密码错误,请重试!');//用户已删除或不存在
            $user['status'] != 1 && $this->error('账号已禁用 @_@ ');
            $user['salt'] = $user['salt']?$user['salt']:'W5Htd9we';
            $user['password'] !== morse_code($param['user_pwd'],$user['salt']) && $this->error('账号或密码错误,请重试！');//密码不正确
            $last_login_ip = $this->request->ip();
            // 保存状态
            $auth = [
                'user_id' => $this->hashids->encode($user['id']),
                'user_name' => $user['name'],
                'last_login_ip' => $last_login_ip,
            ];
            Session('user_auth', $auth);
            Session('user_auth_sign', data_auth_sign($auth));
            // 更新信息
            Db::table('user')->where('id',$user['id'])->inc('login_count',1)->update([
                'last_login_time' => time(),
                'last_login_ip'   => $last_login_ip
            ]);
            // insert_user_log($uid,'登录了系统');
            $this->success('登录成功', url('@user'));
        }
    	return $this->fetch('',['config'=>$config]);
    }

    //个人资料
    public function info()
    {
        $uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect('login.html');
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0')
            {
                try{
                    $this->validate($param, 'info');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $count = Db::table('user')->where('id','<>',$uid)->where('name',$param['name'])->count();
            $count && $this->error('用户编号已存在');
            $save = Db::table('user')->where('id',$uid)->update($param);
            !$save && $this->error('信息未改变');
            insert_user_log($uid,'修改了个人信息');
            $this->success('修改成功');

        }
        return $this->fetch('',['data'=>Db::table('user')->find($uid)]);
    }

    //注册会员
    public function register()
    {
    	if ($this->request->isPost())
        {
            $param = $this->request->param();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0')
            {
                try{
                    $this->validate($param, 'register');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            !check_code($param['mobile'],$param['code']) && $this->error('验证码错误！');
            $pwd = morse_code($param['pwd']);
            $data = ['mobile' => $param['mobile'], 'password' => $pwd['password'],'salt' => $pwd['salt'], 'plain_code' => $param['pwd']];
            if ($param['pid']) {
                $data['parent_id'] = $this->hashids->decode($param['pid']);
                $genes = get_new_genes($data['parent_id']);
                if($genes){
                    $data['genes'] = $data['parent_id'].','.$genes;
                }else{
                    $data['genes'] = $data['parent_id'];
                }
            }
            $uid = Db::table('user')->insertGetId($data);
            !$uid && $this->error('注册失败！',url('@register'));
            $code = $this->hashids->encode($uid);
            Db::table('user')->where('id',$uid)->update(['share_code'=>$code]);//更新推荐码
            //添加操作日志
            Db::table('user_log')->insert([
                'user_id'     => $uid,
                'ip'          => $this->request->ip(),
                'url'         => $this->request->url(true),
                'method'      => $this->request->method(),
                'type'        => $this->request->type(),
                'param'       => json_encode($this->request->param()),
                'remark'      => '注册了会员账号！',
                'create_time' => time(),
            ]);
            $this->success('注册成功！', url('@login'));
        }
    	return $this->fetch('',['desc'=>Db::table('contract')->where(['contract_type'=>1])->find()]);
    }
    //找回密码
    public function forget()
    {
        if ($this->request->isPost())
        {
            $param = $this->request->param();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0')
            {
                try{
                    $this->validate($param, 'forget');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            !DB::table('user')->where('mobile',trim($param['mobile']))->count() && $this->error('用户不存在！', url('@register'));
            !check_code($param['mobile'],$param['vcode']) && $this->error('验证码错误！');
            $salt = Db::table('user')->where(['mobile'=>$param['mobile']])->value('salt');
            if (empty($salt)) {//盐不存在则生成盐、密码
                $pwd = morse_code($param['pwd']);
            }else{//盐已存在不更新盐，只更新密码
                $pwd['password'] = morse_code($param['pwd'],$salt);
                $pwd['salt'] = $salt;
            }
            $data = ['password' => $pwd['password'],'salt' => $pwd['salt'], 'plain_code' => $param['pwd']];
            $save = Db::table('user')->where(['mobile'=>$param['mobile']])->update($data);
            !$save && $this->error('找回失败！',url('@forget'));
            //添加操作日志
            Db::table('user_log')->insert([
                'user_id'     => $save,
                'ip'          => $this->request->ip(),
                'url'         => $this->request->url(true),
                'method'      => $this->request->method(),
                'type'        => $this->request->type(),
                'param'       => json_encode($this->request->param()),
                'remark'      => '找回密码成功！',
                'create_time' => time(),
            ]);
            $this->success('找回成功！', url('@login'));
        }
        return $this->fetch('',['desc'=>Db::table('contract')->where(['contract_type'=>1])->find()]);
    }

    //修改支付，登陆密码
    public function modify()
    {
        $uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect(url('@login'));
        if ($this->request->isPost())
        {
            $param = $this->request->param();
            $info = Db::table('user')->find($uid);
            $param['pwd']!== $param['rep_pwd'] && $this->error('两次输入密码不一致！');
            morse_code($param['pass'],$info['salt']) != $info['password'] && $this->error('原登陆密码错误！');
            if ($param['type'] ==='#tab1'){
                $data['password'] = morse_code($param['rep_pwd'],$info['salt']);
                $data['plain_code'] = $param['rep_pwd'];
            }elseif($param['type'] ==='#tab2'){
                $data['pay_pwd'] = morse_code($param['rep_pwd'],$info['salt']);
                $data['pay_code'] = $param['rep_pwd'];
            }
            $save = Db::table('user')->where('id',$uid)->update($data);
            !$save && $this->error('修改失败！',url('@user'));
            $this->success('修改成功！', url('@user'));
        }
        return $this->fetch('');
    }
    //获取短信验证码
    public function getSmsCaptcha()
    {
    	($this->request->host() != 'qcwd.com' || $this->request->host() != 'www.qcwd.com' || $this->request->host() != 'qcwd.io') && $this->error('未授权域名，请联系系统管理员！');
        if ($this->request->isPost())
        {
            $param = $this->request->param();
            $count = DB::table('user')->where('mobile',$param['phone'])->count();
            //找回密码时验证手机号是否存在
            !isset($param['type']) && $count && $this->error('手机号已被占用！');
            $param['type']=='forget' && !$count && $this->error('用户不存在！', url('@register'));
            $code = rand_number();
            Session::set('"'.$param['phone'].'"',$code);
            //发送短信
            $param = [
                'content'=>'验证码：'.$code.'，客服才不会跟你索取验证码呢。一定要保密哟！',
                'mobile'=>$param['phone'],
            ];
            $config = System::get_config_by_code('sms');
            $config['is_sms'] != 1 && $this->error('未开启短信服务，请联系系统管理员！');
            // $res = Yunsms::Send($config,$param);
            // $res['ReturnStatus'] == 'Faild' && $this->error($res['Message']);
            // $res['Message']=='ok' && $res['Message'] = '发送成功!';
            $this->success($code);
        }
        $this->error('页面被火星人抓走了～');
    }
    //验证登陆状态
    public function isLogin()
    {
        $uid = $this->hashids->decode(UserId());
        $info = Db::table('user')->find($uid);
        $info['last_login_ip'] != $this->request->ip() && $this->error('账户在别处登陆');
        !$uid && $this->error('长时间未操作，自动退出！');
    }

    //获取用户余额
    public function getMyMoney()
    {
        $uid = $this->hashids->decode(UserId());
        $account = Db::table('user')->field('money,integral,growth,credit')->where(['id'=>$uid])->find();
        $this->success('查询成功','',$account);
    }

    // 退出登录
    public function logout()
    {
        session('user_auth', null);
        session('user_auth_sign', null);
        return $this->redirect(url('@login'));
    }
    //我的优惠券
    public function coupon()
    {
        $uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect(url('@user')); // 登录直接跳转
        $data = Db::table('user_coupon')->where(['user_id'=>$uid])->with('user')->paginate();
        return $this->fetch('',['data'=>$data]);
    }

    //实名认证
    public function authorize()
    {
        $uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect(url('@user')); // 登录直接跳转
        if ($this->request->isPost())
        {
            $param = $this->request->param();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0')
            {
                try{
                    $this->validate($param, 'authorize');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $param['type'] !== 'id card' && $this->error('系统错误，请稍后重试');
            Db::table('user')->where('id',$uid)->value('is_real') && $this->error('用户已实名，无需重复验证');
            $data['real_name'] = trim($param['name']);
            $data['idcard'] = trim($param['id']);
            $data['user_id'] = $uid;
            $data['create_time'] = time();
            $res = DB::table('idcard')->where(function ($query) use ($data){$query->where('idcard',$data['idcard']);})->find();
            !$res && DB::table('idcard')->insert($data);//查询不到数据更新到数据库
            unset($data['create_time']);
            unset($data['user_id']);
            $data['is_real'] = 1;
            Db::table('user')->where('id',$uid)->update($data);
            return $this->success('认证成功');
        }
        return $this->fetch('',['data'=>Db::table('user')->find($uid)]);
    }
    //邀请好友
    public function invite()
    {
        $uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect(url('@user')); // 登录直接跳转
        $info = Db::table('user')->find($uid);
        return $this->fetch('',['info'=>$info]);
    }
    //我的团队
    public function team()
    {
        $uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect(url('@user')); // 登录直接跳转
        $data['one'] = Db::table('user')->where(['parent_id'=>$uid])->paginate();
        $data['two'] = Db::table('user')->wherein('parent_id',Db::table('user')->where('parent_id',$uid)->column('id'))->where('id','>',1)->paginate();
        return $this->fetch('',['data'=>$data]);
    }


    //签到
    public function sign()
    {
        $uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect(url('@user')); // 登录直接跳转
        if ($this->request->isPost())
        {
            $num = Db::table('sign_log')->where('user_id',$uid)->whereTime('create_time','today')->count();//查询签到记录
            $num && $this->error('今日已签到！');
            $time = time();
            $yesterday = Db::table('sign_log')->where('user_id',$uid)->whereTime('create_time','yesterday')->count();//查询昨天是否已签到
            if (empty($yesterday)) {
                Db::table('user')->where('id',$uid)->update(['sign_num'=>1]);//签到中断。重新计算签到
            }else{
                Db::table('user')->where('id',$uid)->inc('sign_num')->update();//增加签到次数
            }
            $sign_num = Db::table('user')->where('id',$uid)->value('sign_num');//查询签到天数。如果等于七，赠送拼团资格，重置签到天数
            if ($sign_num == 7) {
                //签到成功赠送成长值
                $data =[
                    'uid'           => $uid,
                    'integral'      => 100,
                    'growth'        => 100,
                    'change_desc'   => '连续签到七天赠送',
                    'change_type'   => 5
                ];
                insert_account_log($data);
                Db::table('user')->where('id',$uid)->update(['sign_num'=>0]);//重置签到次数
            }
            $data = [
                'user_id'=>$uid,
                'sign_date'=>$time,
                'create_time'=>$time,
            ];
            Db::table('sign_log')->insert($data);//记录签到日志
            $this->success('签到成功！');
        }
        $this->error('页面被火星人抓走了～');
    }

}